import re
from _datetime import datetime
from _datetime import timedelta

# 有“1分钟前” “今天 10:09" "2月16日 8：19” 三种形式分别为type1、type2、type3
# 还有一种 2017-05-27 19:42:32
# 中文字符    type1 = re.compile(r'\d+[\u4e00-\u9fa5]+')


def caltime(str):
    try:
        t = datetime.strptime(str.strip(), "%Y-%m-%d %H:%M:%S")
        return t
    except Exception:
        pass
    time = datetime.now()
    type1 = re.compile(r'\d+分钟')
    type2 = re.compile(r'今天')
    type3 = re.compile(r'\d+月')
    Type1 = type1.match(str)
    if(Type1 is not None):
        t1 = re.compile(r'\d+')
        d = int(t1.match(str).group())
        delta = timedelta(minutes=d)
        time = time - delta
        return time
    Type2 = type2.match(str)
    if(Type2 is not None):
        t2 = re.compile(r'\d+')
        results = t2.findall(str)
        h = int(results[0])
        m = int(results[1])
        time = time.replace(hour=h, minute=m)
        return time
    Type3 = type3.match(str)
    if(Type3 is not None):
        t3 = re.compile(r'\d+')
        results = t3.findall(str)
        month = int(results[0])
        day = int(results[1])
        hour = int(results[2])
        minute = int(results[3])
        time = time.replace(month=month, day=day, hour=hour, minute=minute)
        return time


if __name__ == "__main__":
    # 测试如下
    print(caltime('4分钟前'))
    print(caltime('今天 15:13'))
    print(caltime('2月16日 8:19'))
    print(caltime('2017-05-27 19:42:32'))
